package hot100;

public class mergeKLists2 {
    public mergeKLists.ListNode mergeKLists(mergeKLists.ListNode[] lists) {
        if(lists.length < 1) {
            return null;
        }
        mergeKLists.ListNode ret = new mergeKLists.ListNode(0);
        ret.next = lists[0];
        //依次合并2个链表
        for(int i = 0; i < lists.length-1;i++) {
            ret.next =  merTowList(ret.next,lists[i+1]);
        }
        return ret.next;

    }
    mergeKLists.ListNode merTowList(mergeKLists.ListNode list1,mergeKLists.ListNode list2) {
        if(list1 == null) {
            return list2;
        }
        if(list2 == null) {
            return list1;
        }
        mergeKLists.ListNode cur = new mergeKLists.ListNode(0);
        mergeKLists.ListNode ret = cur;
        while(list1 != null && list2 != null) {
            if(list1.val < list2.val) {
                cur.next = list1;
                list1 = list1.next;
            }else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        if(list1 == null) {
            while(list2 != null) {
                cur.next = list2;
                cur = cur.next;
                list2 = list2.next;
            }
        }
        if(list2 == null) {
            while(list1 != null) {
                cur.next = list1;
                cur = cur.next;
                list1 = list1.next;
            }
        }
        //返回合并后的链表头节点
        return ret.next;
    }
}
